package com.amumu.netctoss.action;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;
import javax.annotation.Resources;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.amumu.netctoss.dao.AdminDao;
import com.amumu.netctoss.entity.Admin;
import com.amumu.netctoss.entity.Privilege;
import com.amumu.netctoss.entity.Role;
import com.amumu.netctoss.util.PrivilegeReader;
/**
 * 
 *登录
 */

public class LoginAction extends BaseAction{
	@Resource
	private AdminDao adminDao;
	private Admin admin;
	private String checkCode;
	
	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	private String errorMsg;
	private String codeMsg;
	
	public String getCodeMsg() {
		return codeMsg;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public Admin getAdmin() {
		return admin;
	}

	public void setAdmin(Admin admin) {
		this.admin = admin;
	}

	public String login(){
		String img = (String)session.get("check_code");
		if(img==null||admin==null||checkCode==null){
			return ERROR;
		}
		if(!img.equals(checkCode.toUpperCase())){
			codeMsg = "验证码错误";
			return ERROR;
		}
		try {
			admin = adminDao.findByCodeAndPwd(admin.getCode(), admin.getPassword());
			if(admin==null){
				errorMsg = "用户名或密码错误，请重试";
				return ERROR;
			}
			session.put("user", admin);
			Set<String> urls = new HashSet<String>();
			for(Role r:admin.getRoles()){
				for(int i:r.getPid()){
					Privilege p = PrivilegeReader.getMapPri().get(i+"");
					urls.addAll(p.getUrls());
				}
			}
			session.put("user.urls", urls);
		} catch (Exception e) {
			errorMsg = "服务器繁忙，请稍后重试";
			e.printStackTrace();
			return ERROR;
		}
		
		return SUCCESS;
	}
	public String logout(){
		if(session!=null){
			session.clear();
		}
		return SUCCESS;
	}

}
